﻿using Castle.Core.Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yto.Common.Dependency;
using Yto.Common.Extensions;
using Yto.Threading;
using Yto.Threading.BackgroundWorkers;
using Yto.Unitwork;

namespace com.ytocargo.Application.AcarsInfos
{
    public class SendAcarsInfoPeriod : TimedBgdWorker, ISendAcarsInfoPeriod, ISingleton
    {
        private readonly ICtnManager _ctnManager;
        private ILogger _logger;
        private IUnitManager _unitManager;
        private readonly IAcarsInfoServices _acarsInfoServices;

        public SendAcarsInfoPeriod(BaseTimer baseTimer,
            ICtnManager ctnManager,
            IAcarsInfoServices acarsInfoServices,
            IUnitManager unitManager)
            : base(baseTimer)
        {
            JobPeriod = int.TryParse(ConfigurationManager.AppSettings["Period"], out int tempValue)
                        ? tempValue : 5000;

            baseTimer.Period = JobPeriod;

            _ctnManager = ctnManager;
            _logger = _ctnManager.IsRegisted<ILoggerFactory>() ?
                _ctnManager.Resolver<ILoggerFactory>().Create(typeof(SendAcarsInfoPeriod))
                : NullLogger.Instance;

            _acarsInfoServices = acarsInfoServices;
            _unitManager = unitManager;
        }
        protected override void DoWork()
        {
            using (var uw = _unitManager.Begin())
            {
                var list = _acarsInfoServices.GetUnSengdListAsync(100).Result;
                if (list != null)
                {
                    list.ForEach(x =>
                    {
                        MqHelper.SendMq("AirLines_ACARS", "CAST.HYT.ACARS", x.TeleContent, _logger);
                        x.SendFlag = true;
                        _acarsInfoServices.UpdateAcarsInfoAsync(x);
                    });
                }
                uw.Complete();
            }
        }

        public int JobPeriod { get; private set; }
    }
}
